import React, { useState } from 'react';
import { Button, Modal, Table, Space, Select, Input, Form, message } from 'antd';
import { connect } from 'react-redux';
import { update_order } from '../../../store/actions/order';
import { EXPRESS_COMPANY } from '../../../store/constants/order';
import './index.scss';

const DistributeModal = props => {
  const { orderItem, type, btnCont, update_order } = props;
  const { orderId, goods, goodsNum, orderState, distribute, consignee, consigneePhone, consigneeAddress, expressCompany, trackingNumber } = orderItem;
  // 表格
  const [checkGoods, setCheckGoods] = useState();
  const width = 200;
  const columns = [
    {
      title: '商品',
      dataIndex: 'goodsName',
    },
    {
      title: '数量',
      dataIndex: 'goodsNum',
    },
    {
      title: '发货状态',
      dataIndex: 'deliverState',
    },
  ];
  // 选中行的数据
  const data = [];
  data.push({ key: orderId, goodsName: goods, goodsNum, deliverState: orderState });
  const rowSelection = {
    onChange: (_, selectedRows) => {
      setCheckGoods(selectedRows[0].goodsName);
    },
  };
  // 表单验证
  const [form] = Form.useForm();
  const trackingNumChk = (rule, val) => {
    // console.log(rule);
    if (!val.trim()) {
      return Promise.reject('请填写物流单号');
    } else if (!/^\d{4}$/.test(Number(val.trim()))) {
      return Promise.reject('请输入4位数字的物流单号');
    } else {
      return Promise.resolve();
    }
  };
  // 消息提示
  const [messageApi, contextHolder] = message.useMessage();
  const error = content => {
    messageApi.open({
      type: 'error',
      content,
    });
  };
  // 模态框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    const { expressCompany, trackingNumber } = form.getFieldValue();
    // console.log(expressCompany, trackingNumber);
    let newState = {};
    // 快递公司和物流单号 都必填
    if (!expressCompany) {
      error('请选择快递公司');
      return;
    }
    if (!trackingNumber) {
      error('请填写物流单号');
      return;
    }
    // 分 发货 和 修改物流
    if (type === 1) {
      // 检查商品勾选
      if (!checkGoods) {
        error('请勾选需要发出的商品');
        return;
      } else {
        newState = { expressCompany, trackingNumber, orderState: '已发货' };
      }
    } else {
      if (!/^\d{4}$/.test(trackingNumber)) return;
      newState = { expressCompany, trackingNumber };
    }
    update_order({ id: orderItem.orderId, newState });
    // 提示
    messageApi.open({
      type: 'success',
      content:'操作成功',
      duration:1
    });
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  return (
    <>
      {contextHolder}
      <Button type='link' onClick={showModal}>
        {btnCont}
      </Button>
      <Modal title='订单发货' open={isModalOpen} onOk={handleOk} onCancel={handleCancel} destroyOnClose>
        {/* 内容 */}
        <p>商品信息</p>
        <Table
          rowSelection={
            type === 1
              ? {
                  type: 'checkbox',
                  ...rowSelection,
                }
              : false
          }
          columns={columns}
          dataSource={data}
          pagination={false}
        />
        <p className='sub-title'>配送信息</p>
        <Space direction='vertical'>
          <Space size={10}>
            <span>配送方式：</span>
            <span>{distribute}</span>
          </Space>
          <Space size={10}>
            <span>收货人：</span>
            <span>
              {consignee} {consigneePhone}
            </span>
          </Space>
          <Space size={10}>
            <span>收货地址：</span>
            <span>{consigneeAddress}</span>
          </Space>
        </Space>
        <p className='sub-title'>物流信息</p>
        <Form form={form} initialValues={type === 1 ? '' : { expressCompany, trackingNumber }} autoComplete='off'>
          <Form.Item label='快递公司' name='expressCompany' rules={[{ required: true, message: '请选择快递公司' }]} hasFeedback>
            <Select style={{ width }} allowClear placeholder='请选择' options={EXPRESS_COMPANY} />
          </Form.Item>
          <Form.Item label='物流单号' name='trackingNumber' rules={[{ required: true, validator: trackingNumChk }]} hasFeedback>
            <Input placeholder='请输入' style={{ width }} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

// 改装组件
export default connect(
  state => ({
    state: state.orderReducer,
  }),
  { update_order }
)(DistributeModal);
